package org.franca.importer.ea;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import org.franca.core.dsl.FrancaIDLHelpers;
import org.franca.core.franca.FModel;
import org.franca.importer.ea.utils.SortException;
import org.franca.importer.ea.utils.EARepositoryAccessor;
import org.franca.importer.ea.utils.FModelSorter;
import org.sparx.Package;

public class ImporterFacade {

	private Package rootPackage = null;
	private Franca2EA importer = null;
	private List<FModel> models = new ArrayList<FModel>();
	private HashMap<FModel, String> containerMap = new HashMap<FModel, String>(); 
	
	public ImporterFacade() {
	}

	public boolean setup(String project, boolean createProject,
			String _rootPackage, boolean createRootPackage) {
				
		// Open an existing EA Project
		EARepositoryAccessor.INSTANCE
				.openProject(project, createProject);

		// Find the root package where to import the franca models
		rootPackage = EARepositoryAccessor.INSTANCE
				.findRootPackage(_rootPackage, createRootPackage);
		
		
		return rootPackage != null;
	}

	public void setImporter(Franca2EA importer) {
		this.importer = importer;
	}

	public void addModel(File francaFile) {
		@SuppressWarnings("deprecation")
		FModel model = FrancaIDLHelpers.instance().loadModel(
				francaFile.getAbsolutePath());
		if(model != null) {
			models.add(model);
			containerMap.put(model, francaFile.getName().split("\\.")[0]);
		}
	}

	/**
	 * @deprecated
	 * @param francaFile
	 */	
	public void addModel(FModel model) {
		models.add(model);
	}

	/**
	 * @deprecated
	 * @param model
	 * @param containerName
	 */
	public void addModel(FModel model, String containerName) {
		models.add(model);
		containerMap.put(model, containerName);
	}

	public boolean processImport() {
		
		FModelSorter fModelDependencyResolver = new FModelSorter(models, containerMap);
		try {
			fModelDependencyResolver.sort();
		} catch (SortException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
					
		for (FModel fModel : fModelDependencyResolver.getSorted()) {
							
			Package p = EARepositoryAccessor.INSTANCE.findLocalPackageForFrancaModel(rootPackage, fModel.getName());
			
			String container = (containerMap.get(fModel));
			if(container == null) {
				container = "Unknown Model Container";
			}
			
			importer.processRootPackage(p, fModel, container);
		}

		rootPackage.Update();
		
		return true;
	}
	
	public void tearDown() {

		models.clear();
		
		containerMap.clear();
		
		EARepositoryAccessor.INSTANCE.closeProject();
		
	}
	
}
